package com.david.reader.view

import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import android.widget.EditText
import android.widget.SeekBar
import android.widget.TextView
import com.david.reader.R

class ReaderMenuDialog:Dialog {
    var page = 0
    var pageCount = 0
    var edit:EditText? = null
    var pageCountText:TextView? = null
    var progress:SeekBar? = null

    var onReaderDialogListener: OnReaderDialogListener? = null

    constructor(context: Context): super(context, R.style.DialogTheme)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window?.setGravity(Gravity.BOTTOM)
        setContentView(R.layout.dialog_reader_menu)

        val params = window?.attributes
        params?.width = WindowManager.LayoutParams.MATCH_PARENT
        params?.height = WindowManager.LayoutParams.WRAP_CONTENT
        window?.attributes = params

        edit = findViewById(R.id.reader_edit_page)
        pageCountText = findViewById(R.id.page_count)
        progress = findViewById(R.id.reader_progress)
        findViewById<View>(R.id.reader_nav_page).setOnClickListener {
            onReaderDialogListener?.onNavPage(edit?.text.toString().toInt())
        }
        findViewById<View>(R.id.reader_pre_page).setOnClickListener {
            onReaderDialogListener?.onPrePage()
        }
        findViewById<View>(R.id.reader_next_page).setOnClickListener {
            onReaderDialogListener?.onNextPage()
        }

        findViewById<SeekBar>(R.id.reader_progress).setOnSeekBarChangeListener(object :SeekBar.OnSeekBarChangeListener{
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                if (fromUser)
                    onReaderDialogListener?.onDragChangePage(progress)
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
            }

        })

        setCurrentPage(page, pageCount)
    }

    fun setCurrentPage(page: Int, pageCount: Int): ReaderMenuDialog {
        this.page = page
        this.pageCount = pageCount
        progress?.progress = ((page/pageCount.toFloat()) * 100).toInt()
        pageCountText?.text = String.format("共%d页", pageCount)
        edit?.setText(page.toString())
        edit?.setSelection(edit!!.length())
        return this
    }

    interface OnReaderDialogListener{
        open fun onPrePage()
        open fun onNextPage()
        open fun onNavPage(page: Int)
        open fun onDragChangePage(progress: Int)
    }
}